<?php

/* * 
 * 挑战参与
 */
namespace Api\Model;
use Think\Model;
class ChallengeJoinModel extends Model {

    //映射
    protected $_map = array(
        'challengeId' => 'challenge_id',
        'challengeVideoUrl' => 'challenge_video_url',
        'coverImageUrl' => 'cover_image_url',
    );

    //添加挑战参与记录
    public function addChallengeJoin($userId) {

        //校验字段
        $validateRules = array(
            array('challenge_id', 'require'),
            array('description', 'require'),
            array('challenge_video_url', 'require'),
            array('cover_image_url', 'require')
        );

        //自动完成
        $autoRules = array(
            array('create_time', 'getCurrentDate',self::MODEL_INSERT,'function'),
            array('user_id', $userId),
            array('collect_count', 0),
            array('comment_count', 0),
        );

        $challengeJoin = $this->validate($validateRules)->auto($autoRules)->create();

        if(!$challengeJoin) {
            return "ERROR_NECESSARY_DATA_NOT_FOUND";
        } else {

            //判断内挑战是否存在
            $challengeRecord = D('challenge')->getChallengeById($challengeJoin['challenge_id']);

            if(isNullOrEmpty($challengeRecord)) {
                return "ERROR_CHALLENGE_NOT_FOUND";
            }

            //判断挑战状态
            if($challengeRecord['status'] != C('CHALLENGE_STATUS.START')) {
                return "ERROR_CHALLENGE_VERIFY_OR_END";
            }

            $challengeRecordMap['challenge_id'] = $challengeJoin['challenge_id'];
            $challengeRecordMap['user_id'] = $challengeJoin['user_id'];

            //判断是否已经参与过挑战
            $challengeRecord = $this->where($challengeRecordMap)->find();

            if(!isNullOrEmpty($challengeRecord)) {
                return "ERROR_CHALLENGE_ALREADY_JOINED";
            }

            $this->add();

            return "SUCCESS";

        }

    }

    //获取挑战参与记录
    public function getChallengeJoinById($id) {

        $challengeJoin = $this->where(array('join_id' => $id))->find();

        return $challengeJoin;

    }

    //根据用户ID获取挑战列表（包含名次）
    public function getChallengeJoinListByUserId($userId, $pageNum) {

        $sql = "SELECT cj.challenge_id, DATE_FORMAT(cj.create_time,'%m-%d') AS create_time, c.challenge_name, c.challenge_image_url, c.join_count, 
                (SELECT COUNT(1) + 1 FROM ff_challenge_join chj
                WHERE chj.challenge_id = cj.challenge_id
                AND chj.collect_count > cj.collect_count) AS rank  /*分数相同,名次并列*/
                FROM ff_challenge_join cj
                LEFT JOIN ff_challenge c
                ON cj.challenge_id = c.challenge_id
                WHERE cj.user_id = " .$userId. "
                ORDER BY cj.create_time ASC
                LIMIT " .($pageNum-1)*C('DEFAULT_PAGE_SIZE') . ',' . C('DEFAULT_PAGE_SIZE');

        $list = M()->query($sql);

        return $list;

    }

    //获取某类别下点赞数量最多的挑战
    public function getChallengeJoinMostCollectByType($challengeType) {

        $map['c.challenge_type'] = $challengeType;

        $challengeJoin = $this->alias('cj')
                    ->join("LEFT JOIN __CHALLENGE__ c ON cj.challenge_id = c.challenge_id")
                    ->join("LEFT JOIN __USER__ u ON cj.user_id = u.user_id")
                    ->field("cj.join_id, c.challenge_id, u.user_id, u.username, u.head_image_url, u.city, 
                           cj.collect_count, cj.challenge_video_url, cj.cover_image_url")
                    ->where($map)
                    ->order("cj.collect_count DESC")
                    ->find();

        return $challengeJoin;

    }

    //获取某主题下点赞数量最多的挑战
    public function getChallengeJoinMostCollectByChallengeId($challengeId) {

        $map['cj.challenge_id'] = $challengeId;

        $challengeJoin = $this->alias('cj')
                    ->join("LEFT JOIN __USER__ u ON cj.user_id = u.user_id")
                    ->field("cj.join_id, u.user_id, u.username, u.head_image_url, u.city, cj.challenge_video_url, cj.cover_image_url")
                    ->where($map)
                    ->order("cj.collect_count DESC")
                    ->find();

        return $challengeJoin;

    }

    //PK榜列表（4条记录）
    public function getChallengeJoinListBasic($challengeType='', $challengeId = '', $userId) {

        if(!isNullOrEmpty($challengeType)) {
            $map['c.challenge_type'] = $challengeType;
        }
        
        if(!isNullOrEmpty($challengeId)) {
            $map['c.challenge_id'] = $challengeId;
        }

        $list = $this->alias('cj')
            ->join("LEFT JOIN __CHALLENGE__ c ON cj.challenge_id = c.challenge_id")
            ->join("LEFT JOIN __USER__ u on cj.user_id = u.user_id")
            ->field("cj.join_id, c.challenge_id, u.user_id, u.username, u.head_image_url, u.city,
            c.challenge_name, c.category_name, cj.collect_count, cj.challenge_video_url, cj.cover_image_url")
            ->where($map)
            ->order("cj.collect_count DESC")
            ->limit(4)
            ->select();

        foreach ($list as &$item) {
            //判断是否为好友
            $item['is_friend'] = D('friend')->checkFriendRelationship($userId,$item['user_id']);
        }

        return $list;

    }

    //PK榜列表
    public function getChallengeJoinList($challengeType, $categoryId = '', $pageNum, $userId) {

        $map['c.challenge_type'] = $challengeType;

        if(!isNullOrEmpty($categoryId)) {
            $map['c.category_id'] = $categoryId;
        }

        $list = $this->alias('cj')
            ->join("LEFT JOIN __CHALLENGE__ c ON cj.challenge_id = c.challenge_id")
            ->join("LEFT JOIN __USER__ u on cj.user_id = u.user_id")
            ->field("cj.join_id, c.challenge_id, u.user_id, u.username, u.head_image_url, u.city,
            c.challenge_name, c.category_name, cj.collect_count, cj.challenge_video_url, cj.cover_image_url")
            ->where($map)
            ->order("cj.collect_count DESC")
            ->limit(($pageNum-1)*C('DEFAULT_PAGE_SIZE') . ',' . C('DEFAULT_PAGE_SIZE'))
            ->select();

        foreach ($list as &$item) {
            //判断是否为好友
            $item['is_friend'] = D('friend')->checkFriendRelationship($userId,$item['user_id']);
        }

        return $list;

    }

    //挑战参与详情页
    public function getChallengeJoinDetailById($id, $userId) {

        $challengeJoin = $this->alias('cj')
                    ->join("LEFT JOIN __CHALLENGE__ c ON cj.challenge_id = c.challenge_id")
                    ->join("LEFT JOIN __USER__ u ON cj.user_id = u.user_id")
                    ->field("cj.join_id, c.challenge_id, c.challenge_name, cj.challenge_video_url, cj.description, cj.collect_count,
                            cj.comment_count, TIMESTAMPDIFF(DAY,cj.create_time,NOW()) as upload_days, u.user_id, u.username, u.head_image_url")
                    ->where(array('join_id' => $id))
                    ->find();

        $challengeJoin['is_follow'] = D('follow')->checkFollow($userId, $challengeJoin['user_id']);

        $rankMap['challenge_id'] = $challengeJoin['challenge_id'];
        $rankMap['collect_count'] = array('gt',$challengeJoin['collect_count']);
        $count = $this->where($rankMap)->count();

        $challengeJoin['rank'] = ++$count;

        return $challengeJoin;

    }

    //查看是否已经报名
    public function checkChallengeJoin($challengeId, $userId) {

        $map['challenge_id'] = $challengeId;
        $map['user_id'] = $userId;

        $challengeJoin = $this->where($map)->find();

        if(!isNullOrEmpty($challengeJoin)) {
            return true;
        } else {
            return false;
        }

    }

}

